/**   
* @Title: UserServiceImplExtension.java 
* @Package com.sllx.service.impl 
* @Description: TODO
* @author A18ccms A18ccms_gmail_com   
* @date 2014-3-1 上午12:20:16 
* @version V1.0   
*/
package com.sllx.aspect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.sllx.service.UserService;
import com.sllx.service.impl.UserServiceImpl;
import com.sllx.util.SessionFactory;
import com.sllx.xmlanalyze.Analyze;


/** 
 * 版权所有(C)2013-2023 
 * 公司名称：
 * 公司地址：
 * 网址:
 * 版本:
 * 文件名：com.sllx.service.impl.UserServiceImplExtension.java 
 * 作者: 张斌 
 * 创建时间: 2014-3-1上午12:20:16  
 * 负责人:  
 * 修改者：  
 * 修改时间：2014-3-1上午12:20:16 
 */

/** 
 * @className_interfaceName: UserServiceImplExtension 
 * @date 2014-3-1 上午12:20:16 
 * @author 张斌
 * @Description: TODO 
 */
public class TransactionManager implements InvocationHandler{
	private Object target;
	private Connection conn; 
	private SessionFactory sessionFactory;
	
	public void setTarget(Object target) {
		this.target = target;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.conn = this.sessionFactory.getConnection();
	}



	/* 
	* <p>Title: invoke</p> 
	* <p>Description: </p> 
	* @param proxy
	* @param method
	* @param args
	* @return
	* @throws Throwable 
	* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) 
	*/
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		beginTransaction();
		Object obj = null;
		try{
			obj = method.invoke(target, args);
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			e.printStackTrace();
		} finally {
			close();
		}
		return obj;
	}
	
	private void beginTransaction() throws ClassNotFoundException, SQLException{
		try {
			conn.setAutoCommit(false);
			System.out.println("开启事务");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void rollbackTransaction(){
		try {
			conn.rollback();
			System.out.println("出错回滚");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void commitTransaction(){
		try {
			conn.commit();
			System.out.println("插入成功");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void close(){
		try {
			conn.close();
			System.out.println("连接关闭");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
